import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


class Message{
    public String from;
    public String to;
    public String message;
}
@WebServlet("/message")
public class hello extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();
//    private List<Message>list=new ArrayList<>();
    String filepath="F:/javaweb/message.txt";
    //把数据存入文件
    //处理从服务器获取的消息数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        List<Message>list=load();
        //进行返回
        objectMapper.writeValue(resp.getWriter(),list);
    }

    private List<Message> load() {
        //从文件中读取数据
        //用于临时存放数据
        List<Message>list=new ArrayList<>();
//        //由于FileReader不能只读一行所以要在外面套一层BufferReader壳
//        try (BufferedReader bufferedReader=new BufferedReader(new FileReader(filepath))){
//            //循环读取
//            while (true) {
//                String s=bufferedReader.readLine();
//                if(s==null){
//                    break;
//                }
//                //把文件按空格进行分割，在文本文件中"\t"为分隔符
//                String[]str=s.split("\t");
//                //把文件中的内容和message中的内容进行一一对应
//                Message message=new Message();
//                message.from=str[0];
//                message.to=str[1];
//                message.message=str[2];
//                list.add(message);
//            }
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        Connection connection=null;
        ResultSet resultSet=null;
        PreparedStatement statement=null;
        try {
            connection=DButil.getConnection();
            String sql="select *from wall";
            statement=connection.prepareStatement(sql);
            resultSet=statement.executeQuery();
            while (resultSet.next()){
                Message message=new Message();
                message.from=resultSet.getString("from");
                message.to=resultSet.getString("to");
                message.message=resultSet.getString("message");
                list.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DButil.close(connection, statement, resultSet);
        }
        return list;
    }
    //服务器处理从客户端提交的消息数据1

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //读取body并解析为json格式
        Message message= objectMapper.readValue(req.getInputStream(),Message.class);
        //把数据写入文件
        save(message);
//        list.add(message);
        //返回一个json格式的数据
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write("{\"ok\":1}");
    }

    private void save(Message message) {
//        try(FileWriter fileWriter=new FileWriter(filepath,true)){
//            fileWriter.write(message.from + "\t" +message.to + "\t" + message.message+ "\n");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        Connection connection=null;
        PreparedStatement statement=null;
            try {
                //1.先和数据库建立连接
                connection=DButil.getConnection();
                //2.来进行拼装sql语句
                String sql="insert into wall values(?,?,?)";
                statement=connection.prepareStatement(sql);
                statement.setString(1,message.from);
                statement.setString(2,message.to);
                statement.setString(3,message.message);
                //3.执行sql
                int ret=statement.executeUpdate();
                if(ret==1){
                    System.out.println("插入成功");
                }else {
                    System.out.println("插入失败");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                DButil.close(connection, statement, null);
            }

    }
}
